home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C/C++ Users Group Library 1996 July
/
C-C++ Users Group Library July 1996.iso
/
listings
/
v_12_07
/
allison
/
destroy6.cpp
< prev
next >
Wrap
C/C++ Source or Header
|
1994-05-02
|
934b
|
60 lines
LISTING 10 - Uses internal state to track a resource
// destroy6.cpp
#include <stdio.h>
void f(char *fname);
main()
{
try
{
f("file1.dat");
}
catch(...)
{
puts("Exception caught in main()");
}
return 0;
}
void f(char *fname)
{
class File
{
FILE *f;
public:
File(const char* fname, const char* mode)
{
f = fopen(fname, mode);
}
~File()
{
if (f)
{
fclose(f);
puts("File closed");
}
}
operator void*() const
{
return f ? (void *) this : 0;
}
};
File x(fname,"r");
if (x)
{
// Use file here
puts("Processing file...");
}
throw 1;
}
/* Output:
Processing file...
File closed
Exception caught in main()
*/